package lol.clann.minecraft.springboot.plugin.service;

import lol.clann.minecraft.springboot.api.annotation.command.Command;
import lol.clann.minecraft.springboot.api.annotation.command.CommandDefine;
import lol.clann.minecraft.springboot.api.bukkit.utils.ServerUtils;
import lol.clann.minecraft.springboot.api.model.CacheItem;
import lol.clann.minecraft.springboot.api.model.ClickCallback;
import lol.clann.minecraft.springboot.api.service.CacheService;
import lol.clann.minecraft.springboot.api.service.ClickCallbackService;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 给玩家发送一条消息,玩家点击后,在指定时间内执行指定的回调
 *
 * @author pyz
 * @date 2019/6/23 1:32 AM
 */
@CommandDefine(name = "springboot")
public class ClickCallbackServiceImpl implements ClickCallbackService {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private ServerUtils serverUtils;

    @Override
    public void addCallback(ClickCallback clickCallback) {
        if (clickCallback == null) {
            return;
        }
        long expire = clickCallback.getTimeout() == -1 ? Long.MAX_VALUE : clickCallback.getTimeout() * 1000000L;
        cacheService.putCacheItem("mc.clickcallback." + clickCallback.getKey(),
                new CacheItem<>()
                        .setData(clickCallback)
                        .setExpireAfterCreate(expire));
    }

    @Command(
            showArgs = "executeCallback <key>",
            onlyOp = false,
            onlyPlayer = true,
            des = "仅供插件使用,玩家请忽视此指令"
    )
    private void executeCallback(Player player, String key) {
        CacheItem<ClickCallback> cache = cacheService.getCacheItem("mc.clickcallback." + key);
        if (cache == null) {
            player.sendMessage(ChatColor.RED + "已失效");
            return;
        }
        ClickCallback callback = cache.getData();
        if (callback.getLimit() <= 0) {
            player.sendMessage(ChatColor.RED + "点击已次数耗尽");
            return;
        }
        if (callback.getPlayers() != null) {
            if (callback.getPlayers().contains(player.getName())) {
                player.sendMessage(ChatColor.RED + "非法操作");
                return;
            }
        }
        if (callback.isAsync()) {
            serverUtils.runTaskAsynchronously(() -> callback.getCallback().accept(player));
        } else {
            callback.getCallback().accept(player);
        }
    }

}
